﻿using System;
using Microsoft.SharePoint;

namespace SharePoint.Orm.SiteBuilders {
	/// <summary>
	/// For adding field link's to content types.
	/// </summary>
	public class FieldLinkBuilder : BuilderBase<SPFieldLink> {
		/// <summary>
		/// Sets defaults, required = false, and hidden = false.
		/// </summary>
		public FieldLinkBuilder() {
			Required = false;
		    IsRequired = false;
			Hidden = false;
		}

		/// <summary>
		/// Required.  The Field to create a link to.
		/// </summary>
		public SPField Field { get; set; }

		/// <summary>
		/// Optional.  If you leave it blank it defaults to false.  It does this because if you leave it off in contenttypes.xml SP makes
		/// it optional, so this is designed to match SP.
		/// </summary>
		[Obsolete("Use the IsRequired instead.")]
		public bool Required { get; set; }
        /// <summary>
        /// Optional.  If you leave it blank it defaults to false.  It does this because if you leave it off in contenttypes.xml SP makes
        /// it optional, so this is designed to match SP.
        /// </summary>
        public bool IsRequired { get; set; }
		/// <summary>
		/// Optional, default = null.  This should rarely be necessary because if you leave it blank it picks up the 
		/// description of the parent Field's display name.
		/// </summary>
		public string DisplayName { get; set; }

		/// <summary>
		/// Optional, default = false.  This should rarely be necessary because Hidden can and should be specified in the parent Field.
		/// </summary>
		public bool Hidden { get; set; }

		/// <summary>
		/// Required.  The content type to add the field link to.
		/// </summary>
		public SPContentType ContentType;

		public override SPFieldLink FindAdd() {
			if (ContentType == null)
				throw new SPOrmException("ContentType is required.");

			SPFieldLink fieldLink = FindOrAddFieldLink(ContentType, Field);
			fieldLink.Required = Required;
		    fieldLink.Required = IsRequired;
			fieldLink.Hidden = Hidden;
			if (!string.IsNullOrEmpty(DisplayName)) {
				fieldLink.DisplayName = DisplayName;
			}

			return fieldLink;
		}

		/// <summary>
		/// Finds, updates, adds a field link based on a field and a content type.
		/// </summary>
		/// <param name="contentType"></param>
		/// <param name="field"></param>
		/// <returns></returns>
		public static SPFieldLink FindOrAddFieldLink(SPContentType contentType, SPField field) {
			if (field == null) {
				throw new ArgumentException("field cannot be null", "field");
			}
			SPFieldLink fieldLink = contentType.FieldLinks[field.InternalName];
			if (fieldLink == null) {
				fieldLink = new SPFieldLink(field);
				contentType.FieldLinks.Add(fieldLink);
			}
			return fieldLink;
		}
	}
}
